package com.gjl.app.view.web.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.google.appengine.repackaged.com.google.common.base.StringUtil;

public class WebUtil {
	
	public static final String CURRENT = "current";
	
	private static final String PREVIOUS = "previous";
	
	private static final String NEXT = "next";
	
	private static final String URL = "url";
	
	private static final String LAST = "last";
	
	public static final String PAGINATED = "paginated";
	
	private static final String RESULT = "result";
	

	/**
	 * 
	 * @param url
	 * @param result
	 * @param startIndex
	 * @param itemNumber
	 * @param request
	 */
	public static void paginate(String url, List<?> result, int itemNumber) {
		//Guard statement
		if (result == null || StringUtil.isEmptyOrWhitespace(url) ) {
			return;
		}
		int total = result.size();
		HttpServletRequest request = ServletActionContext.getRequest();
		//Pagination is not needed
		if (total <= itemNumber) {
			request.setAttribute(RESULT, result);
			return;
		} else {
			int startIndex = 0;
			if(request.getParameter(WebUtil.CURRENT) != null) {
				String currentValue = request.getParameter(WebUtil.CURRENT);
				startIndex = Integer.valueOf(currentValue);
			}
			int totalPage = result.size() / itemNumber;
			if (result.size() % itemNumber != 0) {
				totalPage ++ ;
			}
			if (startIndex * itemNumber > total) {
				startIndex = 0;
			}
			if ( (startIndex + 1) * itemNumber <= result.size()) {
				request.setAttribute(RESULT, result.subList(startIndex * itemNumber, (startIndex + 1) * itemNumber));
			} else {
				request.setAttribute(RESULT, result.subList(startIndex * itemNumber, result.size()));
			}
			request.setAttribute(PAGINATED, true);
			request.setAttribute(URL, url);
			request.setAttribute(CURRENT, startIndex);
			if (startIndex > 0) {
				request.setAttribute(PREVIOUS, startIndex - 1);
			}
			if((startIndex + 1) * itemNumber < total) {
				request.setAttribute(NEXT, startIndex + 1);
				request.setAttribute(LAST, totalPage - 1);
			}
		}
	}
}
